/*
 * Description: tags-menu.js
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Chengming.Li
 * Date: 2020/12/22 14:22
 */
const state = {
  // 缓存组件页面
  catch_components: [],
  // 菜单项
  tagsList: [{ path: '/Todo', label: '首页', name: 'Todo' }] //
}
const mutations = {
  // 如果切换到英文状态下 label不刷新修改为英文
  SET_TAG_LABEL(state) {
    for (const tag of state.tagsList) {
      tag.label = this.getters['menu/getMenuNameById'](tag.path)
    }
  },
  // 跳转页面执行
  SELECT_MENU(state, menu) {
    const result = state.tagsList.findIndex(item => item.path === menu.menuId)
    // 如果等于-1说明tagsList不存在那么插入，否则什么都不做
    // result === -1 ? state.tagsList.push({ path: menu.menuId, label: menu.menuName }) : ''
    // 新页面插入到首页后面的生成标签
    result === -1
      ? state.tagsList.splice(1, 0, { path: menu.menuId, label: menu.label, name: menu.name })
      : ''
  },
  // 关闭标签
  CLOSE_TAG(state, menu) {
    const result = state.tagsList.findIndex(item => item.path === menu.path)
    state.tagsList.splice(result, 1)
  },

  // 添加keepalive缓存addKeepAliveCache
  ADD_KEEP_ALIVE_CACHE(state, val) {
    // 首页不缓存
    if (val === 'Todo') return
    // 添加时判断，如果该组件已存在，则不添加

    if (state.catch_components.indexOf(val) === -1) {
      // 不存在，缓存页面
      state.catch_components.push(val)
    }
  },
  // 删除keepAlive缓存 removeKeepAliveCache
  REMOVE_KEEP_ALIVE_CACHE(state, val) {
    const cache = state.catch_components
    for (let i = 0; i < cache.length; i++) {
      if (cache[i] === val) {
        cache.splice(i, 1)
      }
    }
    state.catch_components = cache
  }
}
const getters = {
  getTagsList: state => state.tagsList,
  getCacheList: state => state.catch_components
}
export default {
  namespaced: true,
  getters,
  state,
  mutations
}
